package com.plian.system.service.pm.property;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.plian.Tools.*;
import com.plian.Tools.pagedata.PageData;
import com.plian.system.cache.PropertyCache;
import com.plian.system.cache.UserCache;
import com.plian.system.config.exception.MyRuntimeException;
import com.plian.system.constant.baseinfo.ValueSetConstant;
import com.plian.system.constant.sys.FormTypeConstant;
import com.plian.system.constant.yth.YthConstant;
import com.plian.system.dao.bt.baseinfo.BaseInfoDao;
import com.plian.system.dao.pm.contributor.ContributorBasicsDao;
import com.plian.system.dao.pm.contributor.ContributorDao;
import com.plian.system.dao.pm.contributor.ContributorRecordDao;
import com.plian.system.dao.pm.partneroutbound.PartnerOutboundBasicsDao;
import com.plian.system.dao.pm.partneroutbound.PartnerOutboundDao;
import com.plian.system.dao.pm.partneroutbound.PartnerOutboundRecordDao;
import com.plian.system.dao.pm.partnersituation.PartnerSituationBascicsDao;
import com.plian.system.dao.pm.partnersituation.PartnerSituationDao;
import com.plian.system.dao.pm.partnersituation.PartnerSituationRecordDao;
import com.plian.system.dao.pm.property.PropertyBasicsDao;
import com.plian.system.dao.pm.property.PropertyDao;
import com.plian.system.dao.pm.property.PropertyRecordDao;
import com.plian.system.dao.pm.propertychange.PropertyChangeDao;
import com.plian.system.dao.pm.propertyout.PropertyOutDao;
import com.plian.system.dao.pm.shareholding.ShareholdingBasicsDao;
import com.plian.system.dao.pm.shareholding.ShareholdingDao;
import com.plian.system.dao.pm.shareholding.ShareholdingRecordDao;
import com.plian.system.dao.sys.file.FileDao;
import com.plian.system.dao.sys.orgzation.OrgzationDao;
import com.plian.system.entity.sys.ApprovalMessage;
import com.plian.system.model.CommonCode;
import com.plian.system.model.ListResult;
import com.plian.system.model.ObjResult;
import com.plian.system.model.page.Page;
import com.plian.system.mybatis.base.BaseFlowService;
import com.plian.system.properties.GzwProperties;
import com.plian.system.service.bt.baseinfo.BaseInfoService;
import com.plian.system.service.sys.file.FileService;
import com.plian.system.service.sys.message.IApprovalMessageService;
import com.plian.system.service.sys.orgzation.OrgzationService;
import com.plian.system.service.wf.FormWorkflowService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.util.StringUtil;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import java.io.InputStream;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.stream.Collectors;

import static com.plian.system.constant.sys.ApprovalMessageTypeConstant.KT_TYPE;
import static com.plian.system.constant.sys.ApprovalMessageTypeConstant.PROPERTY;
import static com.plian.system.constant.sys.FormStatusConstant.*;
import static com.plian.system.constant.sys.FormTypeConstant.PM_PROPERTY_FORM;

@Slf4j
@Service
public class PropertyService implements BaseFlowService {
    @Autowired
    PropertyDao propertyDao;
    @Autowired
    ContributorDao contributorDao;
    @Autowired
    ShareholdingDao shareholdingDao;
    @Autowired
    PartnerSituationDao partnersituationDao;
    @Autowired
    PartnerOutboundDao partneroutboundDao;
    @Autowired
    PropertyBasicsDao propertyBasicsDao;
    @Autowired
    ContributorBasicsDao contributorBasicsDao;
    @Autowired
    ShareholdingBasicsDao shareholdingBasicsDao;
    @Autowired
    PartnerSituationBascicsDao partnerSituationBascicsDao;
    @Autowired
    PartnerOutboundBasicsDao partnerOutboundBasicsDao;
    @Autowired
    PropertyRecordDao propertyRecordDao;
    @Autowired
    ContributorRecordDao contributorRecordDao;
    @Autowired
    ShareholdingRecordDao shareholdingRecordDao;
    @Autowired
    PartnerSituationRecordDao partnerSituationRecordDao;
    @Autowired
    PartnerOutboundRecordDao partnerOutboundRecordDao;
    @Autowired
    FileService fileService;
    @Autowired
    OrgzationDao orgzationDao;
    @Autowired
    BaseInfoDao baseInfoDao;
    @Autowired
    PropertyChangeDao propertyChangeDao;
    @Autowired
    PropertyOutDao propertyOutDao;
    @Autowired
    @Lazy
    private FormWorkflowService formWorkflowService;
    @Autowired
    FileDao fileDao;
    @Autowired
    private BaseInfoService baseInfoService;
    @Autowired
    private OrgzationService orgzationService;

    @Autowired
    private IPropertyBasicsService propertyBasicsService;

    @Autowired
    private IApprovalMessageService approvalMessageService;

//    @Autowired TODO DEL
//    private IEnterpriseAssociationService enterpriseAssociationService;

    @Autowired
    private GzwProperties gzwProperties;

    @Transactional(rollbackFor = RuntimeException.class)
    public ObjResult save(PageData pd) {
        ObjResult objResult;
        try {
            //主表主键
            String pro_id = UuidUtil.get32UUID();
            //资本情况
            objResult = new ObjResult(CommonCode.SUCCESS);
            if (Tools.notEmpty(pd.getString("isStash"))) {
                pd.put("status", "-1");
            } else {
                pd.put("status", "0");
            }
            //主表
            pd.put("id", pro_id);
            pd.put("formType", FormTypeConstant.PM_PROPERTY_FORM);
            pd.put("fillOrgId", TokenUtil.getTokenOrgId());
            pd.put("createTime", new Date());
            pd.put("createUser", TokenUtil.getTokenUserId());
            pd.put("updateTime", new Date());
            pd.put("updateUser", TokenUtil.getTokenUserId());
            pd.put("competentOrganization", TokenUtil.getCompetentOrganization());
            List<String> majorIndustries_list = (List<String>) pd.get("majorIndustries");
            String majorIndustries = "";
            if (majorIndustries_list != null && majorIndustries_list.size() > 0) {
                majorIndustries = StringUtil.join(majorIndustries_list.toArray(), ",");
            }
            pd.put("majorIndustries", majorIndustries);

            //匹配组织树
            PageData org = orgzationService.findByName(pd.getString("orgName"), TokenUtil.getCompetentOrganization());
            if (org != null && org.size() > 0) {
                pd.put("orgId", org.getString("id"));
            }
            //保存主表
            propertyDao.save(pd);
            //出资人情况
            //出资人情况
            List<PageData> list_con = (List<PageData>) pd.get("list_con");
            ObjectMapper mapper = new ObjectMapper();
            List<PageData> listCon = mapper.convertValue(list_con, new TypeReference<List<PageData>>() {
            });
            if (listCon != null && listCon.size() > 0) {
                saveCon(listCon, pro_id);
            }
            //境外控股人
            if ("1".equals(pd.getString("nature"))) {
                //出资人情况
                List<PageData> list_share = (List<PageData>) pd.get("list_share");
                List<PageData> listShare = mapper.convertValue(list_share, new TypeReference<List<PageData>>() {
                });
                if (listCon != null && listCon.size() > 0) {
                    saveShare(listShare, pro_id);
                }
            }

            //合伙人
            if ("2".equals(pd.getString("nature"))) {
                //保存从表: 合伙人登记-情况
                List<PageData> list_PartnerSituation = mapper.convertValue(pd.get("listPartnerSituation"), new TypeReference<List<PageData>>() {
                });
                savePartnerSituation(list_PartnerSituation, pro_id);
                //保存从表: 对外投资情况
                List<PageData> list_PartnerOutbound = mapper.convertValue(pd.get("listPartnerOutbound"), new TypeReference<List<PageData>>() {
                });
                savePartnerOutbound(list_PartnerOutbound, pro_id);
            }

            fileSave(pd, pro_id);
            HashMap<String, Object> processVariable = new HashMap<>();
            formWorkflowService.startProcessAndSimulate(pro_id, pd.getString("formType"), processVariable);
        } catch (MyRuntimeException Exception) {
            throw Exception;
        } catch (Exception e) {
            log.error(ExceptionUtils.getFullStackTrace(e));
            throw new MyRuntimeException(new ObjResult(CommonCode.ERROR));
        }
        return objResult;
    }

    /**
     * 附件处理
     *
     * @param pd
     */
    private void fileSave(PageData pd, String id) {
        List<HashMap> list = new ArrayList<>();
        for (int i = 1; i <= 9; i++) {
            List<HashMap> l = (List<HashMap>) pd.get("f" + i);
            if (l != null && l.size() > 0) {
                for (HashMap hashMap : l) {
                    hashMap.put("type", "f" + i);
                    list.add(hashMap);
                }
            }
        }
        //保存附件
        fileService.saveAll(id, list);
    }


    /**
     * 附件处理
     *
     * @param pd
     */
    private void fileEdit(PageData pd, String id) {
        List<HashMap> list = new ArrayList<>();
        for (int i = 1; i <= 9; i++) {
            List<HashMap> l = (List<HashMap>) pd.get("f" + i);
            if (l != null && l.size() > 0) {
                for (HashMap hashMap : l) {
                    hashMap.put("type", "f" + i);
                    list.add(hashMap);
                }
            }
        }
        //修改附件
        fileService.edit(id, list);
    }

    private void fileList(PageData pd) throws Exception {
        List<PageData> l = fileDao.findParentId(pd.getString("id"));
        for (int i = 1; i <= 9; i++) {
            List<PageData> l2 = new ArrayList<>();
            for (PageData pageData : l) {
                if (pageData.getString("type").equals("f" + i)) {
                    pageData.put("itFileName", pageData.getString("fileName"));
                    pageData.put("viewFileName", pageData.getString("fileName"));
                    String fileName = pageData.getString("fileName");
                    //文件后缀
                    String fileTyle = fileName.substring(fileName.lastIndexOf("."));
                    if (!"pdf".equalsIgnoreCase(fileTyle)) {
                        BigDecimal bigDecimal = new BigDecimal(pageData.getString("fileSize"));
                        BigDecimal b = bigDecimal.divide(new BigDecimal("1048576"), 2, RoundingMode.HALF_UP);
                        if (b.floatValue() <= 20) {
                            pageData.put("isPrint", true);
                        } else {
                            pageData.put("isPrint", false);
                        }
                    } else {
                        pageData.put("isPrint", true);
                    }

                    if (Tools.notEmpty(fileName)) {
                        fileName = fileName.substring(19);
                        pageData.put("fileName", fileName);
                    }
                    l2.add(pageData);
//                    break;
                }
            }
            pd.put("f" + i, l2);
        }
    }

    @Transactional(rollbackFor = RuntimeException.class)
    public ObjResult edit(PageData pd) {
        ObjResult objResult;
        try {
            //资本情况
            objResult = new ObjResult(CommonCode.SUCCESS);
            if (Tools.notEmpty(pd.getString("isStash"))) {
                pd.put("status", "-1");
            } else {
                PageData p2 = propertyDao.findbyid(pd.getString("id"));
                if (!"2".equals(p2.getString("status"))) {
                    pd.put("status", "0");
                }
            }
            //匹配组织树
            PageData org = orgzationService.findByName(pd.getString("orgName"), TokenUtil.getCompetentOrganization());
            if (org != null && org.size() > 0) {
                pd.put("orgId", org.getString("id"));
            }
            String pro_id = pd.getString("id");
            pd.put("updateTime", new Date());
            pd.put("updateUser", TokenUtil.getTokenUserId());
            List<String> majorIndustries_list = (List<String>) pd.get("majorIndustries");
            String majorIndustries = "";
            if (majorIndustries_list != null && majorIndustries_list.size() > 0) {
                majorIndustries = StringUtil.join(majorIndustries_list.toArray(), ",");
            }
            pd.put("majorIndustries", majorIndustries);
            propertyDao.edit(pd);

            contributorDao.del_parentId(pd.getString("id"));
            //出资人情况
            List<PageData> list_con = (List<PageData>) pd.get("list_con");
            ObjectMapper mapper = new ObjectMapper();
            List<PageData> listCon = mapper.convertValue(list_con, new TypeReference<List<PageData>>() {
            });
            if (listCon != null && listCon.size() > 0) {
                saveCon(listCon, pro_id);
            }
            //境外控股人
            if ("1".equals(pd.getString("nature"))) {
                //出资人情况
                List<PageData> list_share = (List<PageData>) pd.get("list_share");
                List<PageData> listShare = mapper.convertValue(list_share, new TypeReference<List<PageData>>() {
                });
                shareholdingDao.del_parentId(pro_id);
                if (listCon != null && listCon.size() > 0) {
                    saveShare(listShare, pro_id);
                }
            }

            //合伙人
            if ("2".equals(pd.getString("nature"))) {
                //修改从表: 合伙人登记-情况
                List<PageData> list_PartnerSituation = mapper.convertValue(pd.get("listPartnerSituation"), new TypeReference<List<PageData>>() {
                });
                partnersituationDao.delPrenteId(pro_id);
                savePartnerSituation(list_PartnerSituation, pro_id);
                //修改从表: 对外投资情况
                List<PageData> list_PartnerOutbound = mapper.convertValue(pd.get("listPartnerOutbound"), new TypeReference<List<PageData>>() {
                });
                partneroutboundDao.delPrenteId(pro_id);
                savePartnerOutbound(list_PartnerOutbound, pro_id);
            }
            fileEdit(pd, pro_id);
            objResult = new ObjResult(CommonCode.SUCCESS);
        } catch (MyRuntimeException Exception) {
            throw Exception;
        } catch (Exception e) {
            log.error(ExceptionUtils.getFullStackTrace(e));
            throw new MyRuntimeException(new ObjResult(CommonCode.ERROR));
        }
        return objResult;
    }

    public ObjResult findbyid(PageData pd) {
        ObjResult objResult;
        String pro_id = pd.getString("id");
        try {
            PageData p = propertyDao.findbyid(pro_id);
            p.put("netWorkingName", netWorkingName(p.getString("netWorking")));
            p.put("stateFundedRelationName", stateFundedRelationName(p.getString("stateFundedRelation")));
            p.put("majorIndustriesNames", industryNames(p.getString("majorIndustries")));
            p.put("majorIndustries", Arrays.asList(p.getString("majorIndustries").split(",")));
            objResult = new ObjResult(CommonCode.SUCCESS);
            objResult.setPageData(p);
        } catch (Exception e) {
            log.error(ExceptionUtils.getFullStackTrace(e));
            objResult = new ObjResult(CommonCode.ERROR);
        }
        return objResult;
    }


    private String netWorkingName(String netWorking) {
        Map<String, String> netWorkingMap = baseInfoService.getChildMap(ValueSetConstant.NET_WORKING_TYPE);
        if (com.plian.Tools.StringUtil.isNotBlank(netWorking) && netWorkingMap.containsKey(netWorking)) {
            return netWorkingMap.get(netWorking);
        }
        return "";
    }

    private String stateFundedRelationName(String stateFundedRelation) {
        Map<String, String> stateFundedRelationMap = baseInfoService.getChildMap(ValueSetConstant.STATE_FUNDED_RELATION);
        if (com.plian.Tools.StringUtil.isNotBlank(stateFundedRelation) && stateFundedRelationMap.containsKey(stateFundedRelation)) {
            return stateFundedRelationMap.get(stateFundedRelation);
        }
        return "";
    }

    /**
     * 产权记录
     *
     * @return
     */
    public ListResult record(PageData pd) {
        //产权登记
        try {
            String initialId = pd.getString("initialId");
            //产权登记
            PageData p = propertyDao.findbyid(initialId);
            //产权记录
            PageData p_r = propertyRecordDao.findbyid(p.getString("id"));
            List<PageData> l = new ArrayList<>();
            PageData pro = new PageData();
            pro.put("updateTime", p_r.getString("updateTime"));
            pro.put("id", p.getString("id"));
            pro.put("formType", p.getString("formType"));
            pro.put("orgName", p.getString("orgName"));
            l.add(pro);


            //产权变动
            List<PageData> list_change = propertyChangeDao.record(initialId);


            //产权注销
            PageData p1 = propertyOutDao.record(initialId);
            if (list_change != null && list_change.size() > 0) {
                l.addAll(list_change);
            }
            if (p1 != null && p1.size() > 0) {
                l.add(p1);
            }

            ListResult listResult = new ListResult(CommonCode.SUCCESS);
            listResult.setList(l);
            return listResult;
        } catch (Exception e) {
            log.error(ExceptionUtils.getFullStackTrace(e));
            throw new MyRuntimeException();
        }
    }


    public ObjResult isRepeat(PageData pd) {
        ObjResult objResult;
        objResult = new ObjResult(CommonCode.SUCCESS);
        PageData p = new PageData();
        p.put("isRepeat", isRepeat1(pd));
        objResult.setPageData(p);
        return objResult;
    }

    /**
     * 校验是否重复
     *
     * @param pd
     * @return
     */
    private String isRepeat1(PageData pd) {
        try {
            boolean a = true;
            boolean nameFlag = true;//企业名称重复标记
            boolean orgCodeFlag = true;//社会信用代码重复标记
            if (Tools.notEmpty(pd.getString("id"))) {
                //未审批的时候才会修改
                PageData pageData = propertyDao.findbyid(pd.getString("id"));
                if (pageData.getString("orgName").equals(pd.getString("orgName"))) {
                    nameFlag = false;
                }
                if (pageData.getString("orgCode").equals(pd.getString("orgCode"))) {
                    orgCodeFlag = false;
                }
                if (pageData.getString("id").equals(pd.getString("pId"))) {
                    return "1";
                }
            } else {
                a = true;
            }
            if (a) {
                pd.put("competentOrganization", TokenUtil.getCompetentOrganization());

                PageData pd1 = new PageData();
                pd1.putAll(pd);
                PageData pd2 = new PageData();
                pd2.putAll(pd);
                pd1.remove("orgCode");
                pd1.put("orgName", pd.getString("orgName"));
                pd2.remove("orgName");
                pd2.put("orgCode", pd.getString("orgCode"));

                if (nameFlag) {
                    List<PageData> l = propertyBasicsDao.list(pd1);
                    if (l != null && l.size() > 0) {
                        return "2";
                    }
                    List<PageData> l2 = propertyChangeDao.listByOrgCodeOrName(pd1);
                    if (l2 != null && l2.size() > 0) {
                        return "2";
                    }
                    List<PageData> l4 = propertyDao.noApprovalList(pd1);
                    if (l4 != null && l4.size() > 0) {
                        return "2";
                    }
                }
                if (orgCodeFlag) {
                    List<PageData> l1 = propertyBasicsDao.list(pd2);
                    if (l1 != null && l1.size() > 0) {
                        return "3";
                    }
                    List<PageData> l3 = propertyChangeDao.listByOrgCodeOrName(pd2);
                    if (l3 != null && l3.size() > 0) {
                        return "3";//信用代码重复
                    }
                    List<PageData> l5 = propertyDao.noApprovalList(pd2);
                    if (l5 != null && l5.size() > 0) {
                        return "3";
                    }
                }
            } else {
                return "0";
            }
            return "0";

        } catch (Exception e) {
            log.error(ExceptionUtils.getFullStackTrace(e));
            throw new MyRuntimeException(new ObjResult(CommonCode.ERROR));
        }
    }

    /**
     * 保存出资人情况
     *
     * @param list_con
     * @param pro_id
     */
    private void saveCon(List<PageData> list_con, String pro_id) throws Exception {
        if (list_con != null && list_con.size() > 0) {
            int i = 1;
            for (PageData pageData : list_con) {
                pageData.put("orderNum", i);
                pageData.put("propertyId", pro_id);
                pageData.put("id", UuidUtil.get32UUID());
                i++;
            }
            contributorDao.saveAll(list_con);
        }
    }

    /**
     * 保存出资人情况
     *
     * @param list_con
     * @param pro_id
     * @param type     1 基础从表，2记录从表
     */
    private void saveCon(List<PageData> list_con, String pro_id, int type) throws Exception {
        if (list_con != null && list_con.size() > 0) {
            for (PageData pageData : list_con) {
                pageData.put("propertyId", pro_id);
            }
            if (type == 1) {
                contributorBasicsDao.saveAll(list_con);
            }
            if (type == 2) {
                contributorRecordDao.saveAll(list_con);
            }
        }
    }

    /**
     * 保存境外控股人
     *
     * @param list_share
     * @param pro_id     主表id
     * @param type       1 基础从表，2记录从表
     */
    private void saveShare(List<PageData> list_share, String pro_id, int type) throws Exception {
        if (list_share != null && list_share.size() > 0) {
            for (PageData pageData : list_share) {
                pageData.put("propertyId", pro_id);
            }
            if (type == 1) {
                shareholdingBasicsDao.saveAll(list_share);
            }
            if (type == 2) {
                shareholdingRecordDao.saveAll(list_share);
            }
        }
    }


    /**
     * 保存合伙人从表
     *
     * @param list    从表列表
     * @param prentId 主键id
     */
    private void savePartnerOutbound(List<PageData> list, String prentId, int type) throws Exception {
        if (list != null && list.size() > 0) {
            for (PageData pageData : list) {
                pageData.put("propertyId", prentId);
            }
            if (type == 1) {
                partnerOutboundBasicsDao.saveAll(list);
            }
            if (type == 2) {
                partnerOutboundRecordDao.saveAll(list);
            }
        }
    }

    /**
     * 保存
     *
     * @param list    从表列表
     * @param prentId 主键id
     */
    private void savePartnerSituation(List<PageData> list, String prentId, int type) throws Exception {
        if (list != null && list.size() > 0) {
            for (PageData pageData : list) {
                pageData.put("propertyId", prentId);
            }
            if (type == 1) {
                partnerSituationBascicsDao.saveAll(list);
            }
            if (type == 2) {
                partnerSituationRecordDao.saveAll(list);
            }
        }
    }


    /**
     * 保存境外控股人
     *
     * @param list_share
     * @param pro_id
     */
    private void saveShare(List<PageData> list_share, String pro_id) throws Exception {
        if (list_share != null && list_share.size() > 0) {
            int i = 1;
            for (PageData pageData : list_share) {
                pageData.put("orderNum", i);
                pageData.put("propertyId", pro_id);
                pageData.put("id", UuidUtil.get32UUID());
                i++;
            }
            shareholdingDao.saveAll(list_share);
        }
    }

    /**
     * 保存
     *
     * @param list    从表列表
     * @param prentId 主键id
     */
    private void savePartnerOutbound(List<PageData> list, String prentId) throws Exception {
        if (list != null && list.size() > 0) {
            for (PageData pageData : list) {
                pageData.put("propertyId", prentId);
                pageData.put("id", UuidUtil.get32UUID());
                List<String> industry_list = (List<String>) pageData.get("industry");
                pageData.put("industry", "");
                if (industry_list != null && industry_list.size() > 0) {
                    String industry = StringUtil.join(industry_list.toArray(), ",");
                    pageData.put("industry", industry);
                }

            }
            partneroutboundDao.saveAll(list);
        }
    }

    /**
     * 保存
     *
     * @param list    从表列表
     * @param prentId 主键id
     */
    private void savePartnerSituation(List<PageData> list, String prentId) throws Exception {
        if (list != null && list.size() > 0) {
            for (PageData pageData : list) {
                pageData.put("propertyId", prentId);
                pageData.put("id", UuidUtil.get32UUID());
            }
            partnersituationDao.saveAll(list);
        }
    }


    /**
     * 查询主表，从表数据
     *
     * @param pd
     * @return
     */
    public ObjResult findbyidAll(PageData pd) {
        String pro_id = pd.getString("id");
        ObjResult objResult;
        try {
            //附件
            PageData p = propertyDao.findbyid(pro_id);
            //出资人情况
            List<PageData> list_con = contributorDao.find_parentId(pro_id);
            if (Tools.notEmpty(p.getString("nature"))) {
                if ("1".equals(p.getString("nature"))) {
                    //单位性质为境外，查询境外控股人-BaseShareholding
                    List<PageData> list_share = shareholdingDao.find_parentId(pro_id);
                    p.put("list_share", list_share);
                }
                if ("2".equals(p.getString("nature"))) {
                    //单位性质为合伙人，查询合伙人登记-情况 - BasePartnerSituation
                    List<PageData> list_PartnerSituation = partnersituationDao.find_parentId(pro_id);
                    p.put("listPartnerSituation", list_PartnerSituation);
                    //合伙人对外投资情况
                    List<PageData> list_PartnerOutbound = partneroutboundDao.find_parentId(pro_id);
                    //查询所属行业
                    List<String> parentId1 = new ArrayList<>();
                    parentId1.add("110");
                    PageData p_o1 = new PageData();
                    p_o1.put("parentId", parentId1);
                    List<Tree> l = baseInfoDao.findTree(p_o1);
                    for (PageData pageData : list_PartnerOutbound) {
                        String industry = pageData.getString("industry");
                        if (Tools.notEmpty(industry)) {
                            //所属行业转换中文
                            pageData.put("industryName", industryNames(industry, l));
                            pageData.put("industry", Arrays.asList(industry.split(",")));
                        }
                    }
                    p.put("listPartnerOutbound", list_PartnerOutbound);
                }
            }
            //注册目的
            p.put("netWorkingName", netWorkingName(p.getString("netWorking")));
            //与国家出资企业的关系
            p.put("stateFundedRelationName", stateFundedRelationName(p.getString("stateFundedRelation")));
            if (Tools.notEmpty(p.getString("majorIndustries"))) {
                //主要行业
                p.put("majorIndustriesNames", industryNames(p.getString("majorIndustries")));
                p.put("majorIndustries", Arrays.asList(p.getString("majorIndustries").split(",")));
            } else {
                p.put("majorIndustriesNames", new ArrayList<>());
                p.put("majorIndustries", new ArrayList<>());
            }


            p.put("list_con", list_con);
            fileList(p);

            objResult = new ObjResult(CommonCode.SUCCESS);
            objResult.setPageData(p);
        } catch (Exception e) {
            log.error(ExceptionUtils.getFullStackTrace(e));
            objResult = new ObjResult(CommonCode.ERROR);
        }
        return objResult;
    }

    /**
     * 根据id删除
     *
     * @param pageData
     * @return
     */
    public ObjResult delid(PageData pageData) {
        ObjResult objResult;
        try {
            List<String> ids = (List<String>) pageData.get("ids");
            propertyDao.del_ids(ids);
            for (String s : ids) {
                formWorkflowService.deleteProcessInstance(s);
            }
            objResult = new ObjResult(CommonCode.SUCCESS);
        } catch (Exception e) {
            log.error(ExceptionUtils.getFullStackTrace(e));
            objResult = new ObjResult(CommonCode.ERROR);
        }
        return objResult;
    }


    /**
     * 根据组织id得到产权树ID
     *
     * @param orgCode
     * @return
     */
    public String findByOrgCode(String orgCode) {
        if (com.plian.Tools.StringUtil.isNotBlank(orgCode)) {
            try {
                PageData data = new PageData();
                data.put("orgCode", orgCode);
                data.put("gzwId", gzwProperties.getId());
                PageData pageData = propertyDao.findByDataSourceId(data);
                if (pageData ==null){
                    return null;
                }
                return pageData.getString("id");
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
        return null;
    }


    /**
     * 审批通过后的操作
     *
     * @param id
     */
    private void registerWith(String id) throws Exception {
        //根据id查询产权数据
        PageData p = propertyDao.findbyid(id);

        //登记记录表
        p.put("initialId", id);
        p.put("propertyId", id);
        p.put("id", id);
        p.put("updateTime", new Date());

        Integer isPrivateMix;
        String actualCapital = p.getString("actualCapital5");
        if (Tools.isEmpty(actualCapital)) {
            actualCapital = "0";
        }
        double d = new BigDecimal(actualCapital).doubleValue();
        if (d > 0) {
            isPrivateMix = 1;
        } else {
            isPrivateMix = 0;
        }
        p.put("isPrivateMix", isPrivateMix);
        //保存记录表
        propertyRecordDao.save(p);
        //保存基础表
        propertyBasicsDao.save(p);
        PropertyCache.update(p.getString("id"));
        propertyBasicsService.changeNewPropertyCode(p.getString("id"), p.getString("parentId"));

        //保存企业章程
        saveAssociation(p);
        //出资人情况
        List<PageData> list_con = contributorDao.find_parentId(id);
        if (list_con != null && list_con.size() > 0) {
            saveCon(list_con, id, 1);
            saveCon(list_con, id, 2);
        }


        String nature = p.getString("nature");
        if ("1".equals(nature)) {
            List<PageData> list_share = shareholdingDao.find_parentId(id);
            if (list_share != null && list_share.size() > 0) {
                saveShare(list_share, id, 1);
                saveShare(list_share, id, 2);
            }
        }
        if ("2".equals(nature)) {
            List<PageData> list_PartnerSituation = partnersituationDao.find_parentId(id);
            List<PageData> list_PartnerOutbound = partneroutboundDao.find_parentId(id);
            savePartnerSituation(list_PartnerSituation, id, 1);
            savePartnerSituation(list_PartnerSituation, id, 2);
            savePartnerOutbound(list_PartnerOutbound, id, 1);
            savePartnerOutbound(list_PartnerOutbound, id, 2);
        }
    }

    /**
     * @Description: //TODO 保存企业章程
     * @Author: Take-off
     * @Date: 9:27 AM 2023/4/6
     * @Param: [pd]
     * @return: void
     **/
    private void saveAssociation(PageData pd) {
        try {
            List<PageData> files = fileDao.findParentId(pd.getString("id"));
            String orgId = pd.getString("orgId");

            if (CollectionUtil.isNotEmpty(files)) {
                Optional<PageData> associationFile = files.stream().filter(m -> com.plian.Tools.StringUtil.isNotBlank(m.getString("type")) && "f5".equals(m.getString("type"))).findFirst();
//                if (associationFile.isPresent()) { //TODO DEL
//                    EnterpriseAssociation enterpriseAssociation = new EnterpriseAssociation();
//                    enterpriseAssociation.setFillingYear(DateUtil.format(new Date(), DateUtil.PATTERN_YEAR));
//                    enterpriseAssociation.setFillingUnitId(orgId);
//                    enterpriseAssociation.setFillingTime(new Date());
//                    PageData file = associationFile.get();
//                    String fileName = file.getString("fileName");
//                    enterpriseAssociation.setFileName(fileName.substring(19));
//                    enterpriseAssociation.setBelongUnitId(orgId);
//                    enterpriseAssociation.setEffectTime(new Date());
//                    enterpriseAssociation.setFileStatus(1);
//                    enterpriseAssociation.setAssociationStatus(1);
//                    enterpriseAssociation.setProId(pd.getString("id"));
//                    enterpriseAssociation.setFillingUnitId(orgId);
//                    enterpriseAssociation.setOrgId(orgId);
//                    HashMap fileMap = new HashMap(file);
//                    fileMap.remove("id");
//                    fileMap.remove("parentId");
//                    fileMap.put("itFileName", fileMap.get("fileName"));
//                    enterpriseAssociation.setDocList(Collections.singletonList(fileMap));
//                    enterpriseAssociationService.submit(enterpriseAssociation);
//                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 查询列表
     *
     * @return
     */
    public ListResult fillingList(PageData pd) {
        ListResult listResult;
        try {
            pd.put("fillOrgId", TokenUtil.getTokenOrgId());
            Page page = new Page(true, pd);
            List<PageData> list = propertyDao.findByFillOrgIdPage(page);

            for (PageData property : list) {
                //境内境外
                String nature = property.getString("nature");
                String natueStr = "";
                if (Tools.notEmpty(nature)) {
                    if ("0".equals(nature)) {
                        natueStr = "境内";
                    } else if ("1".equals(nature)) {
                        natueStr = "境外";
                    } else if ("2".equals(nature)) {
                        natueStr = "合伙人";
                    }
                }
                property.put("nature", natueStr);
            }
            listSort(list);
            listResult = new ListResult(CommonCode.SUCCESS);
            listResult.setList(list);
            listResult.setTotal(page.getTotal());


        } catch (Exception e) {
            log.error(ExceptionUtils.getFullStackTrace(e));
            listResult = new ListResult(CommonCode.ERROR);
        }
        return listResult;
    }

    private void listSort(List<PageData> list) {
        //list 集合倒叙排序
        list.sort((a1, a2) -> {
            try {
                Date time1 = (Date) a1.get("updateTime");
                Date time2 = (Date) a2.get("updateTime");
                int status1 = a1.getInteger("status");
                int status2 = a2.getInteger("status");

                if (status1 > status2) {
                    return 1;
                }

                if (status1 < status2) {
                    return -1;
                }

                if (time1.getTime() > time2.getTime()) {
                    return -1;
                } else if (time1.getTime() == time2.getTime()) {
                    return 0;
                } else {
                    return 1;
                }
            } catch (Exception e) {
                log.error(ExceptionUtils.getFullStackTrace(e));
            }
            return 1;
        });
    }

    /**
     * 查询最新的一条列表数据
     *
     * @return
     */
    public ListResult list(PageData p1) {
        try {

            List<PageData> arrayList = new ArrayList<>();
            PageData pd = propertyDao.findByorgId(TokenUtil.getTokenOrgId());
            if (pd != null) {
                TreeUtli treeUtli = new TreeUtli();
                List<PageData> list_all = propertyDao.list(null);
                List<PageData> l = treeUtli.getChlidList(pd.getString("id"), list_all, null);
                arrayList.add(pd);
                arrayList.addAll(l);

                //模糊查询
                String keyWord = p1.getString("keyword");
                if (Tools.notEmpty(keyWord)) {
                    arrayList = arrayList.stream().filter(pageData ->
                            pageData.getString("orgName").contains(keyWord)
                    ).collect(Collectors.toList());
                }
                listSort(arrayList);

//                    p.put("parentId",pd.getString("id"));
//                    arrayList=propertyDao.list(p);
            }
//            }else{
//                PageData p=new PageData();
//                p.put("parentId",p1.getString("parentId"));
//                arrayList=propertyDao.list(p);
//            }
            ListResult listResult = new ListResult(CommonCode.SUCCESS);
            listResult.setTotal(arrayList.size());
            if (p1.containsKey("pageNumber")) {
                int PageNumber = p1.getInteger("pageNumber");
                int PageSize = p1.getInteger("pageSize");
                int pageTotal = (PageNumber - 1) * PageSize;
                int pageTotal1 = PageNumber * PageSize;
                if (arrayList.size() < pageTotal1) {
                    arrayList = arrayList.subList(pageTotal, arrayList.size());
                } else {
                    arrayList = arrayList.subList(pageTotal, pageTotal1);
                }
            }


            listResult.setList(valueListSet(arrayList));

            return listResult;
        } catch (Exception e) {
            log.error(ExceptionUtils.getFullStackTrace(e));
            throw new MyRuntimeException();
        }
    }

    /**
     * code 转中文
     *
     * @param arrayList
     * @return
     * @throws Exception
     */
    private List<PageData> valueListSet(List<PageData> arrayList) throws Exception {
        List<String> parentId = new ArrayList<>();
        parentId.add("002");
        parentId.add("064");
        parentId.add("045");
        parentId.add("001");
        PageData p_o = new PageData();
        p_o.put("parentId", parentId);
        List<Tree> trees = baseInfoDao.findTree(p_o);

        PageData p_o1 = new PageData();
        List<String> hy = new ArrayList<>();
        //行业
        hy.add("110");
        p_o1.put("parentId", hy);
        List<Tree> trees1 = baseInfoDao.findTree(p_o1);
        List<PageData> l = new ArrayList<>();
        for (PageData pro : arrayList) {
            PageData p = new PageData();
            p.putAll(pro);
            String nature = pro.getString("nature");
            //名称
            p.put("orgName", pro.getString("orgName"));
            //统一信用编码
            p.put("orgCode", pro.getString("orgCode"));
            //国家出资企业
            p.put("stateFundedName", pro.getString("stateFundedName"));
            //国资监管机构
            String stateOwnedInstitution = pro.getString("stateOwnedInstitution");
            if (Tools.isEmpty(stateOwnedInstitution)) {
                stateOwnedInstitution = "";
            } else {
                stateOwnedInstitution = getBaseName(trees, stateOwnedInstitution);
            }
            p.put("stateOwnedInstitution", stateOwnedInstitution);
            //注册日期
            p.put("aicRegDate", pro.getString("aicRegDate"));
            //注册资本
            String regCapital = Tools.notEmpty(pro.getString("regCapital")) ? pro.getString("regCapital") : "0";
            BigDecimal b_regCapital = new BigDecimal(regCapital).setScale(3, RoundingMode.UP);
            p.put("regCapital", b_regCapital.toPlainString());

            if (Tools.notEmpty(nature)) {
                //实收资本
                if ("2".equals(nature)) {
                    String paidCapital = Tools.notEmpty(pro.getString("paidCapital")) ? pro.getString("paidCapital") : "0";
                    BigDecimal b_paidCapital = new BigDecimal(paidCapital).setScale(3, RoundingMode.UP);
                    p.put("actualCapital6", b_paidCapital.toPlainString());
                } else {
                    String actualCapital6 = Tools.notEmpty(pro.getString("actualCapital6")) ? pro.getString("actualCapital6") : "0";
                    BigDecimal b_actualCapital6 = new BigDecimal(actualCapital6).setScale(3, RoundingMode.UP);
                    p.put("actualCapital6", b_actualCapital6.toPlainString());
                }
            }


            //国有资本
            String actualCapital1 = Tools.notEmpty(pro.getString("actualCapital1")) ? pro.getString("actualCapital1") : "0";
            BigDecimal b_actualCapital1 = new BigDecimal(actualCapital1).setScale(3, RoundingMode.UP);
            p.put("actualCapital1", b_actualCapital1.toPlainString());
            //组织形式
            String organizationForm = pro.getString("organizationForm");
            if (Tools.isEmpty(organizationForm)) {
                organizationForm = "";
            } else {
                organizationForm = getBaseName(trees, organizationForm);
            }
            p.put("organizationForm", organizationForm);
            //企业类别
            String orgCategory = pro.getString("orgCategory");
            if (Tools.isEmpty(orgCategory)) {
                orgCategory = "";
            } else {
                orgCategory = getBaseName(trees, orgCategory);
            }
            p.put("orgCategory", orgCategory);
            //注册地
            p.put("regAddress", pro.getString("regAddress"));
            //所属行业
            String majorIndustries1 = pro.getString("majorIndustries");
            String majorIndustriesNames = "";
            if (Tools.notEmpty(majorIndustries1)) {
                List<String> majorIndustries = industryNames(majorIndustries1, trees1);
                majorIndustriesNames = String.join("，", majorIndustries);
            }
            p.put("majorIndustries", majorIndustriesNames);
            //产权级次
            String orgGradation = pro.getString("orgGradation");
            if (Tools.isEmpty(orgGradation)) {
                orgGradation = "";
            } else {
                orgGradation = getBaseName(trees, orgGradation);
            }
            p.put("orgGradation", orgGradation);
            //境内境外
            String str_nature = "";
            if (Tools.notEmpty(nature)) {
                if ("0".equals(nature)) {
                    str_nature = "境内";
                } else if ("1".equals(nature)) {
                    str_nature = "境外";
                } else if ("2".equals(nature)) {
                    str_nature = "合伙人";
                }
            }
            p.put("nature", str_nature);
            //是否混改企业
            String isReform = "";
            String actualCapital = pro.getString("actualCapital6");
            if (Tools.isEmpty(actualCapital)) {
                actualCapital = "0";
            }
            double d = new BigDecimal(actualCapital).doubleValue();
            if (d > 0) {
                isReform = "是";
            } else {
                isReform = "否";
            }
            p.put("isReform", isReform);
            p.put("formType", pro.getString("formType"));
            p.put("id", pro.getString("id"));
            l.add(p);
        }
        return l;
    }

    private String getBaseName(List<Tree> list, String code) {
        String name = "";
        for (Tree tree : list) {
            if (tree.getCode().equals(code)) {
                name = tree.getName();
                break;
            }
        }
        return name;
    }


    /**
     * 提交单据
     *
     * @param formId 单据id
     */
    public HashMap<String,Object> commit(String formId){
        try {
            PageData p=propertyDao.findbyid(formId);
            if(Tools.isEmpty(p.getString("nature"))){
               throw new MyRuntimeException("请完善数据！！！");
            }
            PageData pageData = new PageData();
            pageData.put("status", String.valueOf(FLOW));
            ArrayList<String> ids = new ArrayList<>();
            ids.add(formId);
            pageData.put("id", ids);
            propertyDao.refer(pageData);
        } catch (Exception e) {
            log.error(ExceptionUtils.getFullStackTrace(e));
            throw new MyRuntimeException("提交失败");
        }
        return new HashMap<String,Object>();
    }

    /**
     * 退回单据
     *
     * @param formId 单据id
     */
    public Boolean reject(String formId, int formState, String comment){
        PageData pageData = new PageData();
        pageData.put("status", String.valueOf(formState));
        pageData.put("id", Collections.singletonList(formId));
        try {
            propertyDao.refer(pageData);
            saveMessage(formId, false, comment);
        } catch (Exception e) {
            log.error(ExceptionUtils.getFullStackTrace(e));
            throw new MyRuntimeException("回退失败");
        }
        return true;
    }

    private void saveMessage(String formId, boolean approval, String comment) throws Exception {
        PageData pd = propertyDao.findbyid(formId);
        String dataSource = pd.getString("dataSource");
        String dataSourceId = pd.getString("dataSourceId");
        if (StringUtils.isNotBlank(dataSource) && StringUtils.isNotBlank(dataSourceId)) {
            ApprovalMessage approvalMessage = new ApprovalMessage();
            approvalMessage.setDataSourceType(KT_TYPE);
            if (dataSource.equals(YthConstant.DATA_NINGBO)) {
                approvalMessage.setDataSourceType(YthConstant.DATA_NINGBO);
                approvalMessage.setFilingUserName(UserCache.userIdToName(TokenUtil.getTokenUserId()));
                approvalMessage.setFormType(FormTypeConstant.PM_PROPERTY_FORM);
            }
            approvalMessage.setDataSourceId(dataSourceId);
            approvalMessage.setType(PROPERTY);
            approvalMessage.setOpinion(comment);
            approvalMessage.setIsApprove(approval ? 2 : 1);
            approvalMessage.setIsSend(1);
            approvalMessageService.save(approvalMessage);
        }
    }

    /**
     * 单据完成后
     *
     * @param formId
     */
    public Boolean finish(String formId) {
        try {
            PageData pageData = new PageData();
            pageData.put("status", String.valueOf(FINISH));
            pageData.put("id", Collections.singletonList(formId));
            propertyDao.refer(pageData);
            saveMessage(formId, true, "审批通过");
            registerWith(formId);
        } catch (Exception e) {
            log.error(ExceptionUtils.getFullStackTrace(e));
            throw new MyRuntimeException("单据流转完成时修改单据状态失败！");
        }
        return true;
    }

    /**
     * 获取所有一级企业
     *
     * @return
     */
    public List<PageData> allFirstCompany() {
        try {
            return propertyBasicsDao.allFirstCompany();
        } catch (Exception e) {
            log.error(ExceptionUtils.getFullStackTrace(e));
            throw new MyRuntimeException("获取所有一级企业失败！");
        }
    }

    /**
     * @param formIds 单据ids
     */
    public List<PageData> findByIds(List<String> formIds) {
        try {
            PageData pageData = new PageData();
            pageData.put("id", formIds);
            //orgName
            return propertyDao.findByIds(pageData);
        } catch (Exception e) {
            log.error(ExceptionUtils.getFullStackTrace(e));
            throw new MyRuntimeException("根据单据id列表查询报表失败！");
        }
    }

    @Override
    public List<Integer> getFormType() {
        return Collections.singletonList(PM_PROPERTY_FORM);
    }


    /**
     * 产权树
     *
     * @return
     */
    public ObjResult chlidList(PageData pd) {
        try {
            PageData org = propertyDao.findByorgId(TokenUtil.getTokenOrgId());
            List<PageData> arrayList = new ArrayList<>();
            if (org != null) {
                if (Tools.notEmpty(pd.getString("id")) &&
                        org.getString("id").equals(pd.getString("id"))) {
                    PageData parent = propertyDao.findbyid(org.getString("parentId"));
                    arrayList.add(parent);
                } else {
                    PageData p = new PageData();
                    p.put("parentId", org.getString("id"));
                    List<PageData> list = propertyDao.list(new PageData());
                    String id = org.getString("id");
                    List<PageData> l = new ArrayList<>();
                    l.add(org);
                    TreeUtli treeUtli = new TreeUtli();
                    arrayList = treeUtli.getChlidList(id, list, l);
                }
            }
            PageData p = new PageData();
            p.put("list", arrayList);
            ObjResult objResult = new ObjResult(CommonCode.SUCCESS);
            objResult.setPageData(p);
            return objResult;
        } catch (Exception e) {
            log.error(ExceptionUtils.getFullStackTrace(e));
            throw new MyRuntimeException();
        }
    }

    public ObjResult chlidTree() {
        PageData org = null;
        try {
            org = propertyDao.findByorgId(TokenUtil.getTokenOrgId());
            List<PageData> arrayList = new ArrayList<>();
            if (org != null) {
                PageData p = new PageData();
                p.put("parentId", org.getString("id"));
                List<PageData> list = propertyDao.list(new PageData());
                String id = org.getString("id");
                TreeUtli treeUtli = new TreeUtli();
                arrayList = treeUtli.getChlid(id, list);
            }
            PageData p = new PageData();
            p.put("list", arrayList);
            ObjResult objResult = new ObjResult(CommonCode.SUCCESS);
            objResult.setPageData(p);
            return objResult;
        } catch (Exception e) {
            log.error(ExceptionUtils.getFullStackTrace(e));
            throw new MyRuntimeException();
        }

    }

    //导入
    public ObjResult upLoad(MultipartHttpServletRequest request) {
        MultipartFile mp = request.getFile("file");
        UploadUtil uploadUtil = new UploadUtil();
        if (mp != null) {
            try {
                InputStream stream = mp.getInputStream();
                //接收文件流
                //将流给工作簿
                org.apache.poi.ss.usermodel.Workbook book = null;
                if ("application/vnd.ms-excel".equals(mp.getContentType())) {
                    book = new HSSFWorkbook(stream);
                } else {
                    book = new XSSFWorkbook(stream);
                }
                //获取第一个sheet页
                Sheet sheet = book.getSheetAt(0);
                PageData p = new PageData();
                List<PageData> list_con = new ArrayList<>();
                List<PageData> list_cap = new ArrayList<>();
                List<PageData> org = orgzationDao.list(null);
                //出资人类别
                List<PageData> categorys = baseInfoDao.findbyParentid("057");

                int a = 0;
                for (int rowNum = 2; rowNum <= sheet.getLastRowNum(); rowNum++) {
                    Row row = sheet.getRow(rowNum);
                    if (null == row) {
                        continue;
                    }
                    switch (rowNum) {
                        case 2:
                            //企业名称
                            String orgName = uploadUtil.getCellValue(row.getCell(2)).trim();
                            PageData o = orgzationDao.findbyid(TokenUtil.getTokenOrgId());
                            if (!o.getString("name").equals(orgName)) {
                                ObjResult objResult = new ObjResult(CommonCode.ERROR);
                                objResult.setMessage("当前单位与导入的单位不匹配");
                                return objResult;
                            }
                            //国家出资企业
                            String stateFundedName = uploadUtil.getCellValue(row.getCell(8)).trim();
                            p.put("orgName", orgName);
                            p.put("stateFundedName", stateFundedName);
                            break;
                        case 3:
                            //产权登记情形
                            String situation = uploadUtil.getCellValue(row.getCell(2)).trim();
                            List<PageData> situations = baseInfoDao.findbyParentid("060");
                            situation = baseCode(situations, situation, "产权登记情形");

                            //注册资本
                            String regCapital = uploadUtil.getCellValue(row.getCell(9)).trim();
                            //币种
                            String currency = uploadUtil.getCellValue(row.getCell(8)).trim();
                            List<PageData> currencys = baseInfoDao.findbyParentid("014");
                            currency = baseCode(currencys, currency, "币种");
                            //货币单位
                            String monetaryUnit = "万元";
                            List<PageData> monetaryUnits = baseInfoDao.findbyParentid("013");
                            monetaryUnit = baseCode(monetaryUnits, monetaryUnit, "货币单位");
                            p.put("situation", situation);
                            p.put("monetaryUnit", monetaryUnit);
                            p.put("currency", currency);
                            p.put("regCapital", regCapital);
                            break;
                        case 4:
                            //设立注册日期
                            String regDate = uploadUtil.getCellValue(row.getCell(2)).trim();
                            //是否已办工商
                            String isBsHandle = uploadUtil.getCellValue(row.getCell(8)).trim();
                            isBsHandle = "是".equals(isBsHandle) ? "0" : "1";
                            p.put("regDate", regDate);
                            p.put("isBsHandle", isBsHandle);
                            break;
                        case 5:
                            //组织机构代码
                            String orgCode = uploadUtil.getCellValue(row.getCell(2)).trim();
                            //工商登记日期
                            String bsDate = uploadUtil.getCellValue(row.getCell(8)).trim();
                            p.put("orgCode", orgCode);
                            p.put("bsDate", bsDate);
                            break;

                        case 6:
                            //主要出资人组织机构代码
                            String capitalOrgcode = uploadUtil.getCellValue(row.getCell(2)).trim();
                            //所属部门
                            String departments = uploadUtil.getCellValue(row.getCell(8)).trim();
//                            List<PageData>  departmentss=baseInfoDao.findbyParentid("013");
//                            departments=baseCode(departmentss,departments,"所属部门");
                            p.put("capitalOrgcode", capitalOrgcode);
                            p.put("departments", departments);
                            break;
                        case 7:
                            //企业类别
                            List<PageData> orgCategorys = baseInfoDao.findbyParentid("045");
                            String orgCategory = uploadUtil.getCellValue(row.getCell(2)).trim();
                            orgCategory = baseCode(orgCategorys, orgCategory, "企业类别");
                            //国资监管机构
                            String stateOwnedInstitution = uploadUtil.getCellValue(row.getCell(8)).trim();
                            List<PageData> stateOwnedInstitutions = baseInfoDao.findbyParentid("064");
                            stateOwnedInstitution = baseCode(stateOwnedInstitutions, stateOwnedInstitution, "国资监管机构");


                            p.put("orgCategory", orgCategory);
                            p.put("stateOwnedInstitution", stateOwnedInstitution);
                            break;
                        case 8:
                            //组织形式
                            String organizationForm = uploadUtil.getCellValue(row.getCell(2)).trim();
                            List<String> parentId = new ArrayList<>();
                            parentId.add("002");
                            PageData p_o = new PageData();
                            p_o.put("parentId", parentId);
                            List<Tree> organizationForms = baseInfoDao.findTree(p_o);
                            organizationForm = baseCode(organizationForms, organizationForm);


                            //主要行业
                            String majorIndustries = uploadUtil.getCellValue(row.getCell(8)).trim();
                            String[] majorIndustriess = majorIndustries.split(";");
                            String[] majorIndustriesCode = new String[majorIndustriess.length];
                            List<String> parentId1 = new ArrayList<>();
                            parentId1.add("112");
                            PageData p_o1 = new PageData();
                            p_o1.put("parentId", parentId1);
                            List<Tree> l = baseInfoDao.findTree(p_o1);

                            for (int i = 0; i < majorIndustriess.length; i++) {
                                String industriess = majorIndustriess[i];
                                majorIndustriesCode[i] = "";
                                for (Tree p1 : l) {
                                    if (p1.getName().trim().equals(industriess)) {
                                        majorIndustriesCode[i] = p1.getCode();
                                    }
                                }
                            }

                            p.put("organizationForm", organizationForm);
                            p.put("majorIndustriesNames", majorIndustriess);
                            p.put("majorIndustries", majorIndustriesCode);
                            break;
                        case 9:
                            //企业级次
                            List<PageData> orgGradations = baseInfoDao.findbyParentid("001");
                            String orgGradation = uploadUtil.getCellValue(row.getCell(2)).trim();
                            orgGradation = baseCode(orgGradations, orgGradation, "企业级次");
                            p.put("orgGradation", orgGradation);
                            break;
                        case 10:
                            //经营状况
                            List<PageData> managementConditions = baseInfoDao.findbyParentid("006");
                            String managementCondition = uploadUtil.getCellValue(row.getCell(2)).trim();
                            managementCondition = baseCode(managementConditions, managementCondition, "经营状况");
                            //是否国家出资企业主业
                            String isStateFunded = uploadUtil.getCellValue(row.getCell(8)).trim();
                            isStateFunded = "是".equals(isStateFunded) ? "0" : "1";
                            p.put("managementCondition", managementCondition);
                            p.put("isStateFunded", isStateFunded);
                            break;
                        case 11:
                            //注册地
                            String regAddress = uploadUtil.getCellValue(row.getCell(2)).trim();
                            //是否境外转投境内企业
                            String isOverseasToDomestic = uploadUtil.getCellValue(row.getCell(8)).trim();
                            isOverseasToDomestic = "是".equals(isOverseasToDomestic) ? "0" : "1";
                            p.put("regAddress", regAddress);
                            p.put("isOverseasToDomestic", isOverseasToDomestic);
                            break;
                    }
                    if (!"合计".equals(uploadUtil.getCellValue(row.getCell(0)).trim())) {
                        if (rowNum >= 14) {
                            PageData p1 = new PageData();
                            //序号
                            p1.put("orderNum", uploadUtil.getCellValue(row.getCell(0)).trim());
                            //出资人名称
                            String contributor = uploadUtil.getCellValue(row.getCell(4)).trim();
                            String code = getOrgId(org, contributor);
                            if ("".equals(code)) {
                                p1.put("contributor", uploadUtil.getCellValue(row.getCell(1)).trim());
                                p1.put("orgId", "");
                                p1.put("isSystem", "1");
                            } else {
                                p1.put("orgId", code);
                                p1.put("contributor", "");
                                p1.put("isSystem", "0");
                            }
                            p1.put("orgCode", uploadUtil.getCellValue(row.getCell(3)).trim());
                            String category = uploadUtil.getCellValue(row.getCell(4)).trim();
                            category = baseCode(categorys, category, "出资人类别");
                            p1.put("category", category);
                            p1.put("contributionAmount", uploadUtil.getCellValue(row.getCell(6)).trim());
                            p1.put("orgPaidCapital", uploadUtil.getCellValue(row.getCell(7)).trim());
                            p1.put("orgSubscribedCapital", uploadUtil.getCellValue(row.getCell(9)).trim());
                            p1.put("equityRatio", uploadUtil.getCellValue(row.getCell(10)).trim());
                            list_con.add(p1);
                            a = rowNum;
                        }
                    } else {
                        break;
                    }
                }
                for (int i = 0; i <= 5; i++) {
                    Row row = sheet.getRow(a + 4 + i);
                    if (null == row) {
                        continue;
                    }
                    PageData p1 = new PageData();
                    p1.put("project", "实收资本");
                    switch (i) {
                        case 0:
                            p1.put("category", "国家出资");
                            p1.put("declarationNumber", uploadUtil.getCellValue(row.getCell(5)).trim());
                            break;
                        case 1:
                            p1.put("category", "国有法人出资");
                            p1.put("declarationNumber", uploadUtil.getCellValue(row.getCell(5)).trim());
                            break;
                        case 2:
                            p1.put("category", "国有绝对控股法人出资");
                            p1.put("declarationNumber", uploadUtil.getCellValue(row.getCell(5)).trim());
                            break;
                        case 3:
                            p1.put("category", "国有实际控制法人出资");
                            p1.put("declarationNumber", uploadUtil.getCellValue(row.getCell(5)).trim());
                            break;
                        case 4:
                            p1.put("category", "其他");
                            p1.put("declarationNumber", uploadUtil.getCellValue(row.getCell(5)).trim());
                            break;
                        case 5:
                            p1.put("category", "合计");
                            p1.put("declarationNumber", uploadUtil.getCellValue(row.getCell(5)).trim());
                            break;
                    }
                    list_cap.add(p1);
                }
                ObjResult objResult = new ObjResult(CommonCode.SUCCESS);
                p.put("list_con", list_con);
                p.put("list_cap", list_cap);
                objResult.setPageData(p);
                return objResult;
            } catch (Exception e) {
                log.error(ExceptionUtils.getFullStackTrace(e));
                throw new MyRuntimeException();
            }
        } else {
            throw new MyRuntimeException();
        }
    }

    private String getOrgId(List<PageData> list, String name) {
        String id = "";
        for (PageData p : list) {
            if (p.getString("name").equals(name)) {
                id = p.getString("name");
                break;
            }
        }
        return id;
    }

    /**
     * 值集编码
     *
     * @param l
     * @param name
     * @return
     */
    private String baseCode(List<PageData> l, String name, String str) {
        String code = "";
        for (PageData pageData : l) {
            if (pageData.getString("name").equals(name)) {
                code = pageData.getString("code");
                break;
            }
        }
        return code;
    }

    private String baseCode(List<Tree> l, String name) {
        String code = "";
        for (Tree tree : l) {
            if (tree.getName().trim().equals(name)) {
                code = tree.getCode();
                break;
            }
        }
        return code;
    }

    /**
     * 行业转换
     *
     * @return
     */
    private List<String> industryNames(String codes) throws Exception {
        List<String> l = Arrays.asList(codes.split(","));
        List<PageData> baseInfo = baseInfoDao.findbycodes(l);
        List l1 = new ArrayList();
        for (String code : l) {
            String s1 = "";
            for (PageData pageData : baseInfo) {
                if (pageData.getString("code").equals(code)) {
                    s1 = pageData.getString("name");
                    break;
                }
            }
            l1.add(s1);
        }
        return l1;
    }

    public void goBackToStash(String formId) {
        try {
            PageData pageData = new PageData();
            pageData.put("status", String.valueOf(UNREVIEWED));
            pageData.put("id", Collections.singletonList(formId));
            propertyDao.refer(pageData);
        } catch (Exception e) {
            log.error(ExceptionUtils.getFullStackTrace(e));
        }
    }

    public ListResult<PageData> reportList(PageData pd) {
        Page page = new Page(false, pd);
        try {
            List<PageData> list = propertyDao.reportListPage(page);
            ListResult listResult = new ListResult(CommonCode.SUCCESS);
            listResult.setList(list);
            listResult.setTotal(page.getTotal());
            return listResult;
        } catch (Exception e) {
            log.error(ExceptionUtils.getFullStackTrace(e));
            throw new MyRuntimeException();
        }
    }

    public ListResult<PageData> reportListPage(PageData pd) {
        Page page = new Page(true, pd);
        try {
            List<PageData> list = propertyDao.reportListPage(page);
            ListResult listResult = new ListResult(CommonCode.SUCCESS);
            listResult.setList(valueListSet(list));
            listResult.setTotal(page.getTotal());
            return listResult;
        } catch (Exception e) {
            log.error(ExceptionUtils.getFullStackTrace(e));
            throw new MyRuntimeException();
        }
    }

    /**
     * 行业转换
     *
     * @return
     */
    private List<String> industryNames(String codes, List<Tree> list) throws Exception {
        String[] l = codes.split(",");
        List l1 = new ArrayList();
        for (String code : l) {
            String s1 = "";
            for (Tree pageData : list) {
                if (pageData.getCode().equals(code)) {
                    s1 = pageData.getName();
                    break;
                }
            }
            l1.add(s1);
        }
        return l1;
    }

}
